package org.scala.javafx.diagnostics

import javafx.scene.Scene
import javafx.scene.input.MouseEvent
import scala.collection.mutable.WeakHashMap
import javafx.event.EventHandler
import javafx.stage.Stage
import javafx.scene.Node
import org.scala.javafx.rich.Enrich._
import org.scala.javafx.io.IndentPrintWriter
import java.io.PrintWriter

object Spy {
  def explore(scene: Scene): Unit = {
    scene.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler[MouseEvent]{
      def handle(event: MouseEvent): Unit = {
        if (event.isShiftDown && event.isControlDown) {
          Spy.on(event.getTarget)
        }
      }
    })
  }
  
  def recurse(out: IndentPrintWriter, item: Object, depth: Int): Unit = {
    if (item != null) {
      out.println(item)
      if (depth >= 0) {
        item._class.getters.foreach { case (name, getter) =>
          out.indent {
            out.print(name + ": ")
            val child = try {
              getter.invoke(item)
            } catch {
              case e => e
            }
            recurse(out, child, depth - 1)
          }
        }
      }
    } else {
      out.println("null")
    }
  }
  
  def on(item: Object) {
    val spyStage = new SpyStage(item)
    spyStage.show()
    val out = new IndentPrintWriter(new PrintWriter(System.out))
    recurse(out, item, 1)
  }
}
